<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
      <!-- 搜索与添加用户 -->
      <el-row :gutter="30">
        <!-- 搜索框 -->
        <el-col :span="8">
          <el-input
            placeholder="请输入用户"
            v-model="getUserListParams.query"
            clearable
            @clear="clearSearchUser"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="searchUser"
            ></el-button>
          </el-input>
        </el-col>
        <!-- 添加用户按钮 -->
        <el-col :span="4">
          <el-button type="primary" @click="showAdduserForm"
            >添加用户</el-button
          >
        </el-col>
      </el-row>
      <!-- 用户列表表格 -->
      <el-table :data="getUserListData" style="width: 100%" border stripe>
        <el-table-column
          type="index"
          label="#"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="username"
          label="姓名"
          width="180"
          align="center"
        >
        </el-table-column>
        <el-table-column prop="email" label="邮箱" width="180" align="center">
        </el-table-column>
        <el-table-column
          prop="mobile"
          label="电话"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="role_name"
          label="角色"
          align="center"
        ></el-table-column>
        <el-table-column label="状态" align="center">
          <!-- 用户状态 -->
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="changeStatus(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="180">
          <!-- 操作用户 -->
          <template slot-scope="scope">
            <!-- 修改用户 -->
            <el-tooltip
              class="item"
              effect="dark"
              content="修改用户"
              placement="top"
              :enterable="false"
            >
              <el-button
                size="mini"
                type="primary"
                icon="el-icon-edit"
                @click="showModUserform(scope.row)"
              ></el-button>
            </el-tooltip>
            <!-- 删除用户 -->
            <el-tooltip
              class="item"
              effect="dark"
              content="删除用户"
              placement="top"
              :enterable="false"
            >
              <el-button
                size="mini"
                type="danger"
                icon="el-icon-delete"
                @click="delUser(scope.row)"
              ></el-button>
            </el-tooltip>
            <!-- 分配权限 -->
            <el-tooltip
              class="item"
              effect="dark"
              content="分配权限"
              placement="top"
              :enterable="false"
            >
              <el-button
                size="mini"
                type="warning"
                icon="el-icon-setting"
                @click="showUserRolesForm(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="getUserListParams.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="5"
        layout="total, sizes, prev, pager, next, jumper"
        :total="userListTotal"
      >
      </el-pagination>
      <!-- 添加用户对话框 -->
      <el-dialog
        title="添加用户"
        :visible.sync="addUserVisible"
        width="50%"
        @close="cloDialog"
      >
        <el-form
          ref="addUserFormRef"
          :rules="addUserRules"
          :model="addUserParams"
          label-width="80px"
          status-icon
        >
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addUserParams.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input
              type="password"
              v-model="addUserParams.password"
              show-password
            ></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input type="email" v-model="addUserParams.email"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="addUserParams.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addUserVisible = false">取 消</el-button>
          <el-button type="primary" @click="subAddUserform">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 修改用户对话框 -->
      <el-dialog title="修改用户" :visible.sync="modUserVisible" width="50%">
        <el-form
          ref="modUserFormRef"
          :model="modUserParams"
          :rules="modUserRules"
          label-width="80px"
          status-icon
        >
          <el-form-item label="用户名" prop="username" disabled>
            <el-input v-model="modUserParams.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input type="email" v-model="modUserParams.email"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="modUserParams.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="modUserVisible = false">取 消</el-button>
          <el-button type="primary" @click="subModUserform">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 分配用户角色对话框 -->
      <el-dialog
        title="分配角色"
        :visible.sync="userRolesVisible"
        width="50%"
        @close="cloUserRoles"
      >
        <div class="userRoles">
          <span>当前用户：</span>{{ this.thisInfo.username }}
        </div>
        <div class="userRoles">
          <span>当前角色：</span>{{ this.thisInfo.role_name }}
        </div>
        <div class="userRoles">
          <span>角色：</span>
          <el-select v-model="selectUserRoleID" placeholder="请选择">
            <el-option
              v-for="item in userRolesList"
              :key="item.id"
              :value="item.id"
              :label="item.roleName"
            >
            </el-option>
          </el-select>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="userRolesVisible = false">取 消</el-button>
          <el-button type="primary" @click="subUserRolesform">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    // 自定义邮箱验证规则
    var emailValidatePass = (rule, value, callback) => {
      var patt = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/

      if (value === '') {
        callback(new Error('请输入邮箱'))
      } else {
        if (patt.test(value)) {
          callback()
        } else {
          callback(new Error('请输入正确的邮箱格式'))
        }
      }
    }
    // 自定义手机号验证规则
    var telValidatePass = (rule, value, callback) => {
      var patt = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/

      if (value === '') {
        callback(new Error('请输入手机号'))
      } else {
        if (patt.test(value)) {
          callback()
        } else {
          callback(new Error('请输入正确的手机号格式'))
        }
      }
    }
    return {
      // 用户列表参数
      getUserListParams: {
        query: '',
        pagenum: 1,
        pagesize: 5
      },
      // 用户列表返回数据
      getUserListData: [],
      // 用户总数
      userListTotal: 0,
      // 是否显示添加用户对话框
      addUserVisible: false,
      // 添加用户参数
      addUserParams: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 添加用户表单验证规则
      addUserRules: {
        username: [
          { required: true, message: '请输入账号', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        email: [
          { validator: emailValidatePass, trigger: 'blur', required: true }
        ],
        mobile: [
          { validator: telValidatePass, trigger: 'blur', required: true }
        ]
      },
      // 是否显示修改用户对话框
      modUserVisible: false,
      // 根据id查询查询到用户参数
      modUserParams: {},
      // 添加用户表单验证规则
      modUserRules: {
        email: [
          { validator: emailValidatePass, trigger: 'blur', required: true }
        ],
        mobile: [
          { validator: telValidatePass, trigger: 'blur', required: true }
        ]
      },
      // 是否显示添加用户角色对话框
      userRolesVisible: false,
      // 当前用户信息
      thisInfo: {
        username: '',
        role_name: '',
        id: ''
      },
      // 用户角色信息
      userRolesList: {},
      // 当前选择框选中角色id
      selectUserRoleID: ''
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    // 获取用户列表
    async getUserList() {
      const { data } = await this.$http.get('users', {
        params: this.getUserListParams
      })
      if (data.meta.status !== 200) {
        return this.$message({
          message: '获取用户列表失败',
          type: 'error'
        })
      }
      console.log('获取用户列表成功')
      // this.$message({
      //   message: '获取用户列表成功',
      //   type: 'success'
      // })
      this.getUserListData = data.data.users
      this.userListTotal = data.data.total
      console.log(this.getUserListData)
    },
    // 每页数量发生改变
    handleSizeChange(val) {
      this.getUserListParams.pagesize = val
      this.getUserList()
    },
    // 当前页发生改变
    handleCurrentChange(val) {
      this.getUserListParams.pagenum = val
      this.getUserList()
    },
    // 改变用户状态
    async changeStatus(row) {
      const { data } = await this.$http.put(
        `users/${row.id}/state/${row.mg_state}`
      )
      console.log(data)
      if (data.meta.status !== 200) {
        return this.$message({
          message: '修改用户状态失败',
          type: 'error'
        })
      }
      this.$message({
        message: '修改用户状态成功',
        type: 'success'
      })
    },
    // 搜索用户
    searchUser() {
      this.getUserList()
    },
    // 清除用户搜索
    clearSearchUser() {
      this.getUserList()
    },
    // 是否显示添加用户表单
    showAdduserForm() {
      this.addUserVisible = true
    },
    // 关闭表单事件
    cloDialog() {
      this.$refs.modUserFormRef.resetFields()
    },
    // 提交添加用户表单
    subAddUserform() {
      this.$refs.addUserFormRef.validate(async valid => {
        if (!valid) return false
        const { data } = await this.$http.post('users', this.addUserParams)
        console.log(data)
        if (data.meta.status !== 201) {
          this.addUserVisible = false
          return this.$message({ message: '添加用户失败', type: 'error' })
        }
        this.$message({ message: '添加用户成功', type: 'success' })
        this.addUserVisible = false
        this.getUserList()
      })
    },
    // 是否显示添加用户表单,并根据id查询用户信息
    async showModUserform(row) {
      console.log(row)
      this.modUserVisible = true
      const { data } = await this.$http.get(`users/${row.id}`)
      if (data.meta.status !== 200) {
        return this.$message({
          message: `id${row.id}的用户查询失败`,
          type: 'error'
        })
      }
      // this.$message({
      //     message:`id:${row.id}的用户查询成功`,
      //     type:'success'
      //   })
      console.log(`id:${row.id}的用户查询成功`)
      this.modUserParams = data.data
      console.log(this.modUserParams)
    },
    // 提交修改用户表单
    subModUserform() {
      this.$refs.modUserFormRef.validate(async valid => {
        if (!valid) return false
        const { data } = await this.$http.put(
          `users/${this.modUserParams.id}`,
          { email: this.modUserParams.email, mobile: this.modUserParams.mobile }
        )
        console.log(data)
        if (data.meta.status !== 200) {
          this.modUserVisible = false
          return this.$message({ message: '修改用户失败', type: 'error' })
        }
        this.$message({ message: '修改用户成功', type: 'success' })
        this.modUserVisible = false
        this.getUserList()
      })
    },
    // 删除用户
    delUser(row) {
      this.$confirm(`是否删除 ${row.username} 用户?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const { data } = await this.$http.delete(`users/${row.id}`)
          if (data.meta.status !== 200) {
            return this.$message({
              type: 'error',
              message: `用户 ${row.username} 删除失败!`
            })
          }
          this.$message({
            type: 'success',
            message: `用户 ${row.username} 删除成功!`
          })
          this.getUserList()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 是否显示添加用户角色表单
    async showUserRolesForm(row) {
      this.thisInfo.username = row.username
      this.thisInfo.role_name = row.role_name
      this.thisInfo.id = row.id
      const { data } = await this.$http.get('roles')
      if (data.meta.status !== 200) {
        return this.$message({
          message: '用户角色查询失败',
          type: 'error'
        })
      }
      // this.$message({
      //     message:"用户角色查询成功",
      //     type:'success'
      //   })
      console.log('用户角色查询成功')
      this.userRolesList = data.data
      this.userRolesVisible = true
    },
    // 用户角色分配
    async subUserRolesform() {
      if (!this.selectUserRoleID) {
        return this.$message({
          message: '未选择用户角色',
          type: 'error'
        })
      }
      const { data } = await this.$http.put(`users/${this.thisInfo.id}/role`, {
        rid: this.selectUserRoleID
      })
      if (data.meta.status !== 200) {
        return this.$message({
          message: '设置用户角色失败',
          type: 'error'
        })
      }
      this.$message({
        message: '设置用户角色成功',
        type: 'success'
      })
      this.getUserList()
      this.userRolesVisible = false
    },
    // 关闭修改用户角色对话框
    cloUserRoles() {
      this.selectUserRoleID = ''
    }
  },
  components: {}
}
</script>

<style lang="less" scoped>
.el-table {
  margin: 20px 0 20px 0;
}
.userRoles {
  margin: 10px 20px;
  font-size: 14px;
  color: #606266;
  > span {
    display: inline-block;
    width: 75px;
    // border: 1px solid black;
  }
}
</style>
